package com.cskaoyan.shopping.service.impl;

import com.cskaoyan.shopping.constants.GlobalConstants;
import com.cskaoyan.shopping.converter.ContentConverter;
import com.cskaoyan.shopping.converter.ProductCateConverter;
import com.cskaoyan.shopping.dal.entitys.ItemCat;
import com.cskaoyan.shopping.dal.entitys.Panel;
import com.cskaoyan.shopping.dal.entitys.PanelContentItem;
import com.cskaoyan.shopping.dal.persistence.ItemCatMapper;
import com.cskaoyan.shopping.dal.persistence.PanelContentMapper;
import com.cskaoyan.shopping.dal.persistence.PanelMapper;
import com.cskaoyan.shopping.dto.PanelContentDto;
import com.cskaoyan.shopping.dto.PanelDto;
import com.cskaoyan.shopping.dto.ProductCateDto;
import com.cskaoyan.shopping.service.IHomeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service

public class IHomeServiceImpl implements IHomeService {
    @Autowired
    PanelMapper panelMapper;

    @Autowired
    PanelContentMapper panelContentMapper;

    @Autowired
    ContentConverter contentConverter;

    @Autowired
    ItemCatMapper itemCatMapper;
    @Autowired
    ProductCateConverter productCateConverter;

    @Override
    public Set<PanelDto> homepage() {
        Set<PanelDto> panelDtos = new HashSet<>();
        // 出现在首页的内容的position值为0,查询版块id
        List<Integer> panelIds = panelMapper.selectPanelIdByPosition(0);
        for (Integer panelId : panelIds) {
            // 根据版块id查询
            List<Panel> panels = panelMapper.selectPanelContentById(panelId);
            for (Panel panel : panels) {
                List<PanelContentItem> panelContentItems = panelContentMapper.selectPanelContentAndProductWithPanelId(panelId);
                panel.setPanelContentItems(panelContentItems);
                PanelDto panelDto = contentConverter.panel2Dto(panel);
                panelDtos.add(panelDto);
            }
        }
        return panelDtos;
    }

    @Override
    public List<PanelContentDto> navigate() {
        // 在tb_panel_content表中查询panelId为0的板块内容，即导航栏
        List<PanelContentItem> panelContentItems =
                panelContentMapper.selectPanelContentAndProductWithPanelId(GlobalConstants.HEADER_PANEL_ID);
        List<PanelContentDto> panelContentDtos = new ArrayList<>();
        for (PanelContentItem panelContentItem : panelContentItems) {
            PanelContentDto panelContentDto = contentConverter.panelContentItem2Dto(panelContentItem);
            panelContentDtos.add(panelContentDto);
        }
        return panelContentDtos;
    }

    @Override
    public List<ProductCateDto> categories() {
        List<ItemCat> itemCats = itemCatMapper.selectAllItemCat();
        List<ProductCateDto> productCateDtos = productCateConverter.items2Dto(itemCats);
        return productCateDtos;
    }
}
